package com.qikux.controller;

import com.qikux.annotation.Component;
import com.qikux.annotation.RequestMapping;
import com.qikux.annotation.RequestMethod;
import com.qikux.annotation.Resource;
import com.qikux.entity.User;
import com.qikux.service.UserService;
import com.qikux.utils.ContextUtils;
import com.qikux.utils.RSAUtils;
import com.qikux.vo.ResultVo;

import javax.servlet.http.HttpServletRequest;

@Component
@RequestMapping("/password")
public class PasswordController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/modify",method = RequestMethod.GET)
    public String modifyPassword(){
        return "modifypass";
    }

    @RequestMapping(value = "/modify",method = RequestMethod.POST)
    public String modifyPassword(HttpServletRequest request){
        String oldPassWord = request.getParameter("oldPassWord");
        String newPassWord = request.getParameter("newPassWord");
        String confirmPassWord = request.getParameter("confirmPassWord");
        ResultVo<?> resultVo = userService.updatePassWord(oldPassWord, newPassWord, confirmPassWord);
        if (!resultVo.isStatus()){
            if (resultVo.getData().equals("noUser")){
                request.setAttribute("errorMsg",resultVo.getMessage());
                return "fail";
            }
            request.setAttribute(String.valueOf(resultVo.getData()),resultVo.getMessage());
            return "modifypass";
        }
        return "redirect:/user/logout";
    }

    @RequestMapping(value = "/find",method = RequestMethod.GET)
    public String findPassWord(){
        return "findpass";
    }


    @RequestMapping(value = "/find",method = RequestMethod.POST)
    public String findPassWord(HttpServletRequest request){
        String tel = request.getParameter("tel");
        String email = request.getParameter("email");
        ResultVo<User> resultVo = userService.findPassWord(tel, email);
        if (!resultVo.isStatus()){
            ContextUtils.getRequest().setAttribute("errorMsg",resultVo.getMessage());
            return "fail";
        }
        return "redirect:/password/active";
    }

    @RequestMapping(value = "/active",method = RequestMethod.GET)
    public String activePassword(HttpServletRequest request){
        String id = request.getParameter("u");
        String password = request.getParameter("n");
        String sign = request.getParameter("sign");
        String message = "n=" + id + "&u=" + password;
        if (!RSAUtils.verify(message,sign)){
            request.setAttribute("errorMsg","数据认证失败,请勿篡改数据");
        }
        userService.initePassword(Long.parseLong(id));

        return "redirect:/user/login";
    }



}
